package com.feimt.controller;

import com.feimt.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 宋孟林
 * @description 图片的上传和下载
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${feimt.path}")
    private String basePath;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){//注意这里的参数名不能乱写，要和前端请求的表单input标签name属性名相同
        log.info("文件信息为：{}", file);
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + suffix;
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        try{
            file.transferTo(new File(basePath + newFileName));
        }catch (IOException e){
            log.error(e.getMessage());
            System.out.println("错误信息为： " + e.getMessage());
        }
        return R.success(newFileName);
    }

    /**
     * 将文件未找到异常和io异常交给全局异常处理器处理
     * @param name name
     * @param response re
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        FileInputStream inputStream = new FileInputStream(new File(basePath + name));
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        int len = 0;
        byte[] aByte = new byte[1024];
        while ((len = inputStream.read(aByte)) != -1){
            outputStream.write(aByte, 0, len);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
    }
}
